package server;

import initializer.ComServerChannelInitializer;
import io.netty.bootstrap.ServerBootstrap;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.nio.NioServerSocketChannel;
import listener.LoopServerSendMessageListener;

public class ComServer {

    private final int port;
    private final ServerBootstrap serverBootstrap;
    private final ComServerChannelInitializer channelInitializer = new ComServerChannelInitializer();
    private final NioEventLoopGroup mainGroup = new NioEventLoopGroup();
    private final NioEventLoopGroup subGroup = new NioEventLoopGroup();

    public ComServer(int port){
        this.port = port;
        this.serverBootstrap = new ServerBootstrap();
    }

    /**
     * 开启服务
     */
    public void start() throws InterruptedException {

        this.serverBootstrap.group(mainGroup, subGroup)
                .channel(NioServerSocketChannel.class)
                .childHandler(channelInitializer);
        serverBootstrap.bind(port).addListener(new LoopServerSendMessageListener()).sync()
        //监听关闭的channel,设置为同步方式
        .channel().closeFuture().sync();
    }
}
